class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int n=nums.size();
        deque<int>q;//记录元素下标
        for(int i=0;i<k;++i)
        {
            //删除队列中比新元素小的元素
            while(!q.empty()&&nums[i]>=nums[q.back()])
            {
                q.pop_back();
            }
            q.push_back(i);//新元素入队
        }
        vector<int>ans={nums[q.front()]};
        for(int i=k;i<n;++i)
        {
            while(!q.empty()&&nums[i]>=nums[q.back()])
            {
                q.pop_back();
            }
            q.push_back(i);
            //保证队列元素下标在窗口内
            while(q.front()<=i-k)
            {
                q.pop_front();
            }
            ans.push_back(nums[q.front()]);
        }
        return ans;
    }
};